package ruifight.member.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import ruifight.member.model.*;
import ruifight.member.model.UserInfoExample.Criteria;
import ruifight.member.model.security.MyUserDetail;
import ruifight.member.service.AccountRecordService;
import ruifight.member.service.CarInfoService;
import ruifight.member.service.MemberInfoService;
import ruifight.member.service.UserInfoService;
import ruifight.member.util.MD5Util;
import ruifight.member.util.ObjUtil;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Member;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Controller
@RequestMapping("/interface")
public class MemberInfoController {

	private static final Logger logger = LoggerFactory.getLogger(MemberInfoController.class);

	@Autowired
	public MemberInfoService memberInfoService;
	@Autowired
	public UserInfoService userInfoService;
	@Autowired
	public CarInfoService carInfoService;
	@Autowired
	public AccountRecordService accountRecordService;

	/**
	 * 添加会员
	 * @param m
	 * @return
	 */
	@RequestMapping("/addMemberInfo")
	@ResponseBody
	public Map<String, Object> addMemberInfo(@RequestBody Map<String, String> m){
		SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
		Map<String, Object> map = new HashMap<String, Object>();
		String userName = m.get("userName");
		String certificateCode = m.get("certificateCode");
		String mobile = m.get("mobile");
		String memberEndDate = m.get("memberEndDate");

		String carBrand = m.get("carBrand");
		String carBuyingDate = m.get("carBuyingDate");
		String insuranceStartDate = m.get("insuranceStartDate");
		String insuranceEndDate = m.get("insuranceEndDate");

		try {
			//保存用户基本信息
			UserInfo userInfo = new UserInfo();
			userInfo.setUserName(userName);
			userInfo.setLoginName(mobile);

			// 验证数据
			UserInfo user = testUserInfo(userInfo);
			if (ObjUtil.isNotNullAndEmpty(user) && user.getUserType() != 2) {
				map.put("state", 0);
				map.put("msg", "手机号已被注册");
			}else{
				if(ObjUtil.isNotNullAndEmpty(user)){
					//保存会员信息
					MemberInfo memberInfo = new MemberInfo();
					memberInfo.setUserInfoId(userInfo.getUserInfoId());
					if(ObjUtil.isNotNullAndEmpty(memberEndDate)){
						memberInfo.setMemberEndDate(sdf.parse(memberEndDate));
					}
					memberInfo.setMemberState(1);
					memberInfo.setCreateDate(new Date());
					memberInfoService.insertSelective(memberInfo);

					//保存车辆信息
					CarInfo carInfo = new CarInfo();
					carInfo.setUserInfoId(userInfo.getUserInfoId());
					carInfo.setCarBrand(carBrand);
					if(ObjUtil.isNotNullAndEmpty(carBuyingDate)){
						carInfo.setCarBuyingDate(sdf.parse(carBuyingDate));
					}
					if(ObjUtil.isNotNullAndEmpty(insuranceStartDate)){
						carInfo.setInsuranceStartDate(sdf.parse(insuranceStartDate));
						carInfo.setInsuranceEndDate(sdf.parse(insuranceEndDate));
					}
					carInfo.setCarState(1);
					carInfo.setCreateDate(new Date());
					carInfoService.insertSelective(carInfo);
					//修改登录账号类型
					user.setUserType(4);
					userInfoService.updateByPrimaryKeySelective(user);
				}else{
					if(ObjUtil.isNotNullAndEmpty(certificateCode)){
						userInfo.setPassword(MD5Util.MD5(certificateCode.substring(12,18)));
					}
					userInfo.setCertificateCode(certificateCode);
					userInfo.setUserType(3);
					userInfo.setMobile(mobile);
					userInfo.setUserState(1);
					userInfo.setCreateDate(new Date());
					userInfoService.insertSelective(userInfo);
					//保存会员信息
					MemberInfo memberInfo = new MemberInfo();
					memberInfo.setUserInfoId(userInfo.getUserInfoId());
					if(ObjUtil.isNotNullAndEmpty(memberEndDate)){
						memberInfo.setMemberEndDate(sdf.parse(memberEndDate));
					}
					memberInfo.setMemberState(1);
					memberInfo.setCreateDate(new Date());
					memberInfoService.insertSelective(memberInfo);

					//保存车辆信息
					CarInfo carInfo = new CarInfo();
					carInfo.setUserInfoId(userInfo.getUserInfoId());
					carInfo.setCarBrand(carBrand);
					if(ObjUtil.isNotNullAndEmpty(carBuyingDate)){
						carInfo.setCarBuyingDate(sdf.parse(carBuyingDate));
					}
					if(ObjUtil.isNotNullAndEmpty(insuranceStartDate)){
						carInfo.setInsuranceStartDate(sdf.parse(insuranceStartDate));
						carInfo.setInsuranceEndDate(sdf.parse(insuranceEndDate));
					}
					carInfo.setCarState(1);
					carInfo.setCreateDate(new Date());
					carInfoService.insertSelective(carInfo);
				}

				map.put("state",1);
				map.put("msg","添加成功");
			}

		}catch (Exception e){
			map.put("state",0);
			map.put("msg","添加失败");
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 修改会员信息
	 * @param memberInfo
	 * @return
	 */
	@RequestMapping("/updateMemberInfo")
	@ResponseBody
	public Map<String, Object> updateMemberInfo(@RequestBody Map<String, Object> paramMap){
		SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String userInfoId = paramMap.get("userInfoId").toString();
			String userName= paramMap.get("userName").toString();
			String certificateCode= paramMap.get("certificateCode").toString();
			String mobile= paramMap.get("mobile").toString();
			String memberInfoId = paramMap.get("memberInfoId").toString();
			String memberEndDate= paramMap.get("memberEndDate").toString();

			UserInfo userInfo = new UserInfo();
			userInfo.setUserInfoId(Long.parseLong(userInfoId));
			userInfo.setUserName(userName);
			userInfo.setCertificateCode(certificateCode);
			userInfo.setMobile(mobile);
			userInfoService.updateByPrimaryKeySelective(userInfo);

			MemberInfo memberInfo = new MemberInfo();
			memberInfo.setMemberInfoId(Long.parseLong(memberInfoId));
			if(ObjUtil.isNotNullAndEmpty(memberEndDate)){
				memberInfo.setMemberEndDate(sdf.parse(memberEndDate));
			}
			memberInfoService.updateByPrimaryKeySelective(memberInfo);
			map.put("state",1);
			map.put("msg","修改成功");
		}catch (Exception e){
			map.put("state",0);
			map.put("msg","修改失败");
			e.printStackTrace();
		}
		return map;
	}
	/**
	 * 删除会员
	 * @param memberInfo
	 * @return
	 */
	@RequestMapping("/delMemberInfo")
	@ResponseBody
	public Map<String, Object> delMemberInfo(@RequestBody MemberInfo memberInfo){
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			memberInfo.setMemberState(0);
			memberInfoService.updateByPrimaryKeySelective(memberInfo);
			UserInfo userInfo = new UserInfo();
			userInfo.setUserInfoId(memberInfo.getUserInfoId());
			userInfo.setUserState(0);
			userInfoService.updateByPrimaryKeySelective(userInfo);
			map.put("state",1);
			map.put("msg","删除成功");
		}catch (Exception e){
			map.put("state",0);
			map.put("msg","删除失败");
			e.printStackTrace();
		}
		return map;
	}
	/**
	 * 获取会员信息
	 * @param memberInfo
	 * @return
	 */
//	@RequestMapping("/getMemberInfo")
//	@ResponseBody
//	public MemberInfo getMemberInfo(){
//		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//		MemberInfoExample memberInfoExample=new MemberInfoExample();
//		memberInfoExample.createCriteria()
//			.andUserInfoIdEqualTo(ud.getUserInfoId())
//			.andMemberStateEqualTo(1);
//		MemberInfo memberInfo=memberInfoService.selectOneByExample(memberInfoExample);
//		return memberInfo;
//	}
	@RequestMapping("/getMemberInfo")
	@ResponseBody
	public Map<String, Object> getMemberInfo(){
		Map<String, Object> map = new HashMap<String, Object>();
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		MemberInfoExample memberInfoExample=new MemberInfoExample();
		memberInfoExample.createCriteria()
				.andUserInfoIdEqualTo(ud.getUserInfoId())
				.andMemberStateEqualTo(1);
		MemberInfo memberInfo=memberInfoService.selectOneByExample(memberInfoExample);
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("draweeId", ud.getUserInfoId());
		Float cumulativeDiscount = accountRecordService.getCumulativeDiscount(paramMap);
		map.put("memberIntegral",memberInfo.getMemberIntegral());
		map.put("memberEndDate",memberInfo.getMemberEndDate());
		map.put("memberInfoId",memberInfo.getMemberInfoId());
		map.put("cumulativeDiscount",cumulativeDiscount);
		return map;
	}

	/**
	 * 会员解绑
	 * @param paramMap
	 * @return
	 */
	@RequestMapping("/memberUntying")
	@ResponseBody
	public Map<String, Object> memberUntying(@RequestBody Map<String, Object> paramMap){
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String userInfoId = paramMap.get("userInfoId").toString();
			String openId= paramMap.get("openId").toString();

			UserInfo userInfo = new UserInfo();
			userInfo.setUserInfoId(Long.parseLong(userInfoId));
			userInfo.setOpenId(openId);
			userInfoService.updateByPrimaryKeySelective(userInfo);
			map.put("state",1);
			map.put("msg","解绑成功");
		} catch (Exception e){
			map.put("state",0);
			map.put("msg","解绑失败");
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 信息校验
	 * @param userInfo
	 * @return
	 */
	public UserInfo testUserInfo(UserInfo userInfo) {
		// 验证账号是否存在
		UserInfoExample userInfoExample = new UserInfoExample();
		Criteria criteria = userInfoExample.createCriteria();
		criteria.andUserStateEqualTo(1);
		criteria.andLoginNameEqualTo(userInfo.getLoginName());
//		criteria.andUserTypeEqualTo(3);
		UserInfo user = userInfoService.selectOneByExample(userInfoExample);
		return user;
	}
}
